<template>
  <div class="paper-list">
    <!-- 头部 -->
    <div class="header">
      <div class="header-top">
        <span class="title">每日一练</span>
        <el-button type="primary" size="small" @click="createPaper">创建试卷</el-button>
      </div>
      <div class="header-bottom">
        <div class="filter-item">
          <span class="filter-label">业务类型</span>
          <el-tree-select
            v-model="selectedBusinessType"
            :data="businessTypeData"
            :render-after-expand="false"
            style="width: 150px"
          />
        </div>
        <div class="filter-item">
          <span class="filter-label">试卷类型</span>
          <el-tree-select
            v-model="selectedExamType"
            :data="examTypeData"
            :render-after-expand="false"
            style="width: 150px"
          />
        </div>
        <div class="filter-item">
          <el-input v-model="input" style="width: 150px" clearable placeholder="输入关键词" />
        </div>
        <div class="filter-item">
          <el-button @click="handleSearch">
            搜索
          </el-button>
        </div>
      </div>
    </div>

    <!-- 内容区：卡片列表 -->
    <div class="content">
      <el-row :gutter="10" justify="start">
        <el-col v-for="(paper, index) in pagedPapers" :key="index" :span="6">
          <el-card
            class="paper-card"
            :body-style="{ padding: '16px', paddingBottom: '0' }"
            shadow="hover"
          >
            <template #header>
              <div class="card-header">
                <span>{{ paper.name }}</span>
              </div>
            </template>

            <div class="paper-info">
              <div class="info-item">
                <div class="value score">{{ paper.totalScore }}</div>
                <span>总分数</span>
              </div>
              <div class="info-item">
                <div class="value pass-score">{{ paper.passingScore }}</div>
                <span>通过分数</span>
              </div>
              <div class="info-item">
                <div class="value question-count">
                  {{ paper.totalQuestions }}
                </div>
                <span>题目数</span>
              </div>
            </div>

            <div class="other-info">
              <div class="info-item-horizontal">
                <span>业务类型</span>
                <div class="value business-type">
                  {{ formatBusinessType(paper.businessType, paper.businessType2, paper.businessType3) }}
                </div>
              </div>
              <div class="info-item-horizontal">
                <span>出题类型</span>
                <div class="value">{{ paper.examType }}</div>
              </div>
              <div class="info-item-horizontal">
                <span>出卷人</span>
                <div class="value">{{ paper.creator }}</div>
              </div>
              <div class="info-item-horizontal">
                <span>创建时间</span>
                <div class="value">{{ paper.createTime }}</div>
              </div>
            </div>

            <template #footer>
              <div class="card-footer">
                <el-button
                  class="small-btn"
                  size="mini"
                  @click="editPaper(paper)"
                  >编辑</el-button
                >
                <el-button
                  class="small-btn"
                  size="mini"
                  type="danger"
                  @click="deletePaperById(paper.id)"
                  >删除</el-button
                >
                <el-button
                  class="small-btn"
                  size="mini"
                  type="primary"
                  @click="viewDetails(paper)"
                  >详情</el-button
                >
              </div>
            </template>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 底部：分页 -->
    <div class="footer">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[8, 16, 20, 24]"
        :total="total"
        layout="total, sizes, prev, pager, next"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 添加抽屉组件 -->
    <el-drawer
      v-model="drawerVisible"
      :size="drawerSize"
      :title="selectedPaper?.name || '试卷详情'"
      direction="rtl"
      :destroy-on-close="true"
    >
      <template #header>
        <div class="drawer-header">
          <h3>{{ selectedPaper?.name || '试卷详情' }}</h3>
          <div class="drawer-actions">
            <el-button 
              type="primary" 
              size="small" 
              @click="handleEditFromDrawer"
            >编辑试卷</el-button>
          </div>
        </div>
      </template>
      
      <!-- 抽屉内容 -->
      <div class="drawer-content">
        <div class="paper-basic-info">
          <div class="info-section">
            <h4>基本信息</h4>
            <el-descriptions :column="2" border>
              <el-descriptions-item label="总分">{{ selectedPaper?.totalScore }}</el-descriptions-item>
              <el-descriptions-item label="通过分数">{{ selectedPaper?.passingScore }}</el-descriptions-item>
              <el-descriptions-item label="题目数量">{{ selectedPaper?.questions?.length || 0 }}</el-descriptions-item>
              <el-descriptions-item label="业务类型">
                {{ formatBusinessType(selectedPaper?.businessType, selectedPaper?.businessType2, selectedPaper?.businessType3) }}
              </el-descriptions-item>
              <el-descriptions-item label="试卷类型">{{ selectedPaper?.examType }}</el-descriptions-item>
              <el-descriptions-item label="创建时间">{{ selectedPaper?.createTime }}</el-descriptions-item>
              <el-descriptions-item label="创建人">{{ selectedPaper?.creator }}</el-descriptions-item>
            </el-descriptions>
          </div>

          <!-- 添加试题列表部分 -->
          <div class="info-section questions-section">
            <h4>试题列表</h4>
            <el-table 
              :data="selectedPaper?.questions || []" 
              style="width: 100%"
              border
              max-height="calc(100vh - 400px)"
            >
              <el-table-column type="index" label="序号" width="60" align="center" />
              <el-table-column prop="title" label="题面" min-width="200" show-overflow-tooltip>
                <template #default="{ row }">
                  <div v-html="row.title"></div>
                </template>
              </el-table-column>
              <el-table-column prop="categoryLevel1" label="一级分类" width="120" />
              <el-table-column prop="categoryLevel2" label="二级分类" width="120" />
              <el-table-column prop="categoryLevel3" label="三级分类" width="120" />
              <el-table-column prop="questionType" label="题型" width="100">
                <template #default="{ row }">
                  <el-tag :type="getQuestionTypeTag(row.questionType)">
                    {{ row.questionType }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="level" label="等级" width="100">
                <template #default="{ row }">
                  <el-tag :type="getDifficultyTag(row.level)">
                    {{ row.level }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="score" label="分数" width="80" align="center" />
            </el-table>
          </div>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from "vue";
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from "element-plus";
import { getExamPapersByPage, deleteExamPaper, getExamPaperDetail } from '@/api/api'

// 获取路由器实例
const router = useRouter();

// 状态定义
const papers = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(8)
const input = ref('')
const selectedBusinessType = ref(null)
const selectedExamType = ref(null)
const drawerVisible = ref(false)
const selectedPaper = ref(null)

// 筛选树数据
const businessTypeData = [
  { value: "全部", label: "全部" },
  { value: "化学", label: "化学" },
  { value: "英语", label: "英语" },
  { value: "生物", label: "生物" },
  { value: "物理", label: "物理" },
  { value: "地理", label: "地理" },
  { value: "历史", label: "历史" },
  { value: "技术", label: "技术" },
  { value: "数学", label: "数学" },
]

const examTypeData = [
  { value: "选择题", label: "选择题" },
  { value: "判断题", label: "判断题" },
  { value: "填空题", label: "填空题" },
]

// 获取试卷列表数据
const fetchPapers = async () => {
  try {
    const params = {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      businessType: selectedBusinessType.value,
      examType: selectedExamType.value,
      keyword: input.value.trim()
    }
    
    const response = await getExamPapersByPage(params)
    if (response.code === 200) {
      papers.value = response.data.items.map(item => ({
        id: item.id,
        name: item.name || item.paperName,
        totalScore: item.totalScore,
        passingScore: item.passScore,
        totalQuestions: item.totalQuestions || item.questions?.length || 0,
        businessType: item.busiTypeName1,
        businessType2: item.busiTypeName2,
        businessType3: item.busiTypeName3,
        examType: mapQuestionType(item.questionType),
        creator: item.createName,
        createTime: item.createTime
      }))
      total.value = response.data.total
    } else {
      ElMessage.error(response.message || '获取试卷列表失败')
    }
  } catch (error) {
    console.error('获取试卷列表失败:', error)
    ElMessage.error('获取试卷列表失败')
  }
}

// 修改题型映射函数
const mapQuestionType = (type) => {
  const typeMap = {
    1: '人工选题',
    2: '随机选题',
    'manual': '人工选题',
    'random': '随机选题'
  }
  return typeMap[type] || '未知类型'
}

// 计算属性
const pagedPapers = computed(() => papers.value)

const drawerSize = computed(() => {
  return `${(window.innerWidth * 2) / 3}px`
})

// 事件处理函数
const handleSizeChange = (size) => {
  pageSize.value = size
  fetchPapers()
}

const handleCurrentChange = (page) => {
  currentPage.value = page
  fetchPapers()
}

const handleSearch = () => {
  currentPage.value = 1
  fetchPapers()
}

const createPaper = () => {
  router.push({
    path: '/mypaper/create',
    query: {
      mode: 'create',
    },
  })
}

const editPaper = async (paper) => {
  console.log('开始编辑试卷:', paper);
  try {
    const response = await getExamPaperDetail(paper.id);
    console.log('获取到试卷详情:', response);
    if (response.code === 200) {
      router.push({
        path: '/mypaper/create',
        query: {
          mode: 'edit',
          paperId: paper.id,
        },
      });
      console.log('已导航到编辑页面, paperId:', paper.id);
    } else {
      ElMessage.error(response.message || '获取试卷详情失败');
    }
  } catch (error) {
    console.error('获取试卷详情失败:', error);
    ElMessage.error('获取试卷详情失败');
  }
}

//删除操作
const deletePaperById = async (paperId) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这份试卷吗？删除后不可恢复',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    const response = await deleteExamPaper(paperId)
    if (response.code === 200) {
      ElMessage.success('删除成功')
      // 重新获取列表数据
      fetchPapers()
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除试卷失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

const viewDetails = async (paper) => {
  try {
    const response = await getExamPaperDetail(paper.id)
    if (response.code === 200) {
      const paperData = response.data
      selectedPaper.value = {
        ...paper,
        questions: paperData.questions.map(question => ({
          id: question.id,
          title: question.qsContent,
          categoryLevel1: question.busiTypeName1,
          categoryLevel2: question.busiTypeName2,
          categoryLevel3: question.busiTypeName3,
          questionType: mapDetailQuestionType(question.questionType),
          level: mapDetailDifficulty(question.level),
          score: question.score || 0
        }))
      }
      drawerVisible.value = true
    } else {
      ElMessage.error(response.message || '获取试卷详情失败')
    }
  } catch (error) {
    console.error('获取试卷详情失败:', error)
    ElMessage.error('获取试卷详情失败')
  }
}

// 添加题型和难度的映射函数（如果还没有的话）
const getQuestionTypeTag = (type) => {
  const map = {
    '单选题': '',
    '多选题': 'success',
    '判断题': 'info',
  }
  return map[type] || ''
}

const getDifficultyTag = (level) => {
  const map = {
    '初级': 'info',
    '中级': 'warning',
    '高级': 'danger'
  }
  return map[level] || ''
}

// 监听筛选条件变化
watch([selectedBusinessType, selectedExamType], () => {
  currentPage.value = 1
  fetchPapers()
})

// 组件挂载时获取数据
onMounted(() => {
  fetchPapers()
})

// 添加格式化业务类型的函数
const formatBusinessType = (type1, type2, type3) => {
  return [type1, type2, type3]
    .filter(Boolean) // 过滤掉空值、null 和 undefined
    .join(' > ')
}

// 添加难度映射函数
const mapDifficulty = (level) => {
  const difficultyMap = {
    1: '初级',
    2: '中级',
    3: '高级'
  }
  return difficultyMap[level] || '未知难度'
}

// 添加详情页面的题型映射函数
const mapDetailQuestionType = (type) => {
  const typeMap = {
    'radio': '单选题',
    'checkbox': '多选题',
    'judge': '判断题',
    'fill': '填空题'
  }
  return typeMap[type] || '未知类型'
}

// 添加详情页面的难度映射函数
const mapDetailDifficulty = (level) => {
  const difficultyMap = {
    1: '初级',
    2: '中级',
    3: '高级'
  }
  return difficultyMap[level] || '未知难度'
}

// 添加 handleEditFromDrawer 方法
const handleEditFromDrawer = async () => {
  if (!selectedPaper.value) return;
  
  try {
    const response = await getExamPaperDetail(selectedPaper.value.id);
    console.log('获取到试卷详情:', response);
    if (response.code === 200) {
      drawerVisible.value = false; // 关闭抽屉
      router.push({
        path: '/mypaper/create',
        query: {
          mode: 'edit',
          paperId: selectedPaper.value.id,
        },
      });
    } else {
      ElMessage.error(response.message || '获取试卷详情失败');
    }
  } catch (error) {
    console.error('获取试卷详情失败:', error);
    ElMessage.error('获取试卷详情失败');
  }
};
</script>

<style scoped>
@import "../css/list.css";
</style>